<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>任务计划</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top: 10px">
      <el-row>
        <el-col :span="2">
          <el-button
            type="primary"
            size="mini"
            @click="addTaskplanDialogVisibal = true"
            >新 增</el-button
          >
        </el-col>
      </el-row>
      <!-- 测试用例列表区域 -->
      <el-table :data="taskplanList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="任务名称" prop="name"> </el-table-column>
        <el-table-column label="执行方法" prop="func"></el-table-column>
        <el-table-column label="执行方式" prop="trigger"></el-table-column>
        <el-table-column label="下次执行时间" prop="next_run_time">
          <template slot-scope="scope">
            {{ scope.row.next_run_time ? scope.row.next_run_time : "——" }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row.next_run_time ? "执行中" : "已暂停" }} -->
            <el-switch
              v-model="scope.row.next_run_time ? true : false"
              @change="changeState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template slot-scope="scope">
            <el-popconfirm
              title="确定执行该任务?"
              @confirm="executeTaskplan(scope.row)"
            >
              <el-button slot="reference" size="mini" type="text"
                >执行</el-button
              >
            </el-popconfirm>
            <el-divider direction="vertical"></el-divider>
            <el-button size="mini" type="text">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm
              title="确定删除该任务?"
              @confirm="deleteTaskplan(scope.row)"
            >
              <el-button slot="reference" size="mini" type="text"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination layout="total" :total="total"> </el-pagination>
    </el-card>

    <!-- 新增任务计划对话框 -->
    <el-dialog
      title="新增任务计划"
      :visible.sync="addTaskplanDialogVisibal"
      width="40%"
    >
      <!-- 内容主体区域 -->
      <el-form label-width="90px" label-suffix=":" ref="addTaskplanFormRef" :model="addTaskplanForm">
        <el-row :gutter="20">
          <el-col :span="12"
            ><el-form-item label="任务名称" prop="name">
              <el-input
                v-model="addTaskplanForm.name"
                size="mini"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="执行方法" prop="func">
              <el-input
                v-model="addTaskplanForm.func"
                size="mini"
                disabled
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="触发器" prop="trigger">
              <el-select
                v-model="addTaskplanForm.trigger"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="addTaskplanForm.trigger == 'interval'"
              label="时间间隔"
              prop="minutes"
            >
              <el-input v-model="addTaskplanForm.minutes" size="mini"
                ><i slot="suffix" style="font-style:normal;margin-right: 10px;"
                  >分钟</i
                ></el-input
              ></el-form-item
            >
            <el-form-item
              v-else-if="addTaskplanForm.trigger == 'date'"
              label="执行日期"
              prop="run_date"
            >
              <el-date-picker
                v-model="addTaskplanForm.run_date"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                size="mini"
                class="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker
            ></el-form-item>
            <el-form-item
              v-else-if="addTaskplanForm.trigger == 'cron'"
              label="cron表达式"
              prop="cron"
            >
              <el-row class="cron">
                <el-col :span="8">
                  <el-input
                    v-model="addTaskplanForm.cron.hour"
                    size="mini"
                    placeholder="0-23"
                    ><i slot="suffix">时</i></el-input
                  >
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model="addTaskplanForm.cron.minute"
                    size="mini"
                    placeholder="0-59"
                    ><i slot="suffix">分</i></el-input
                  >
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model="addTaskplanForm.cron.second"
                    size="mini"
                    placeholder="0-59"
                    ><i slot="suffix">秒</i></el-input
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="执行脚本" prop="tests">
              <el-cascader
                :props="cascaderProps"
                v-model="addTaskplanForm.tests"
                separator="/"
                clearable
                size="mini"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddTaskplanForm('addTaskplanFormRef')" size="mini">取 消</el-button>
        <el-button type="primary" @click="addJob()" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let that = this;
    return {
      // 测试任务数据列表
      taskplanList: [],
      // 任务计划总数
      total: 0,
      //  控制新增任务计划对话框的显示与隐藏
      addTaskplanDialogVisibal: false,

      addTaskplanForm: {
        name: "",
        func: "build_job",
        type: "",
        trigger: "interval",
        minutes: "",
        run_date: "",
        cron: {
          hour: "",
          minute: "",
          second: "",
        },
        tests: ''
      },
      options: [
        {
          value: "interval",
          label: "interval",
        },
        {
          value: "date",
          label: "date",
        },
        {
          value: "cron",
          label: "cron",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      cascaderProps: {
         multiple: true,
         expandTrigger: 'hover',
         checkStrictly: true,
         //级联选择器懒加载
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          console.log(level, node);
          if (level == 0) {
            that.getEpic().then((list1) => {
              let arr = list1.map((e) => ({ value: e.value, label: e.label}));
              resolve(arr); // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            });
          }

          if (level == 1) {
            // let { value } = node;
            console.log(node)
            that.getFeature(node.value).then(list2=>{
              let arr = list2.map((e) => ({ value: e.value, label: e.label}));
              resolve(arr);
            });
          }

          if (level == 2) {
            // let { value } = node;
            console.log(node)
            console.log(node.value)
            that.getStory(node.parent.value, node.value).then(list2=>{
              let arr = list2.map((e) => ({ value: e.value, label: e.label}));
              resolve(arr);
            });
          }

          if (level == 3) {
            // let { value } = node;
            console.log(level)
            console.log(node.value)
            that.getTestscript(node.parent.parent.value,node.parent.value, node.value).then(list3=>{
              let arr = list3.map((e) => ({ value: e.value, label: e.label ,leaf:true}));
              resolve(arr);
            });
          }

        }
      },
    };
  },

  created() {
    this.getTaskplanList();
  },

  methods: {
    //   获取任务计划
    async getTaskplanList() {
      const { data: res } = await this.$http.get("/taskplan/get_jobs");
      // 查询失败
      if (res.code !== 200) {
        return this.$message.error("获取用例数据失败");
      }
      this.taskplanList = res.data;
      this.total = res.count;
    },

    // 切换任务状态
    async changeState(taskplan) {
      if (taskplan.next_run_time) {
        const { data: res } = await this.$http.get(
          `/taskplan/pause_job?id=${taskplan.id}`
        );
        if (res.code !== 200) {
          return this.$message.error("停用失败");
        }
        this.$message.success("停用成功");
      } else {
        const { data: res } = await this.$http.get(
          `/taskplan/resume_job?id=${taskplan.id}`
        );
        if (res.code !== 200) {
          return this.$message.error("启动失败");
        }
        this.$message.success("启动成功");
      }
      this.getTaskplanList();
    },

    // 执行任务
    async executeTaskplan(taskplan) {
      const { data: res } = await this.$http.get(
        `/taskplan/run_job?id=${taskplan.id}`
      );
      if (res.code !== 200) {
        return this.$message.error("操作失败");
      }
      this.$message.success("操作成功");
    },

    // 删除任务
    async deleteTaskplan(taskplan) {
      const { data: res } = await this.$http.get(
        `/taskplan/remove_job?id=${taskplan.id}`
      );
      if (res.code !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getTaskplanList();
    },

    // 获取epic
    async getEpic() {
      const {data: res} = await this.$http.get(
        `/taskplan/get_epic`
      );
      if (res.code !== 200) {
        return this.$message.error("查询失败");
      }
      console.log(res.data)
      return res.data
    },

    // 获取feature
    async getFeature(param) {
      const {data: res} = await this.$http.get(
        `/taskplan/get_feature?epic=${param}`
      );
      if (res.code !== 200) {
        return this.$message.error("查询失败");
      }
      console.log(res.data)
      return res.data
    },

    // 获取story
    async getStory(epic, feature) {
      const {data: res} = await this.$http.get(
        `/taskplan/get_story?epic=${epic}&feature=${feature}`
      );
      if (res.code !== 200) {
        return this.$message.error("查询失败");
      }
      console.log(res.data)
      return res.data
    },

    // 获取testscript
    async getTestscript(epic, feature, story) {
      const {data: res} = await this.$http.get(
        `/taskplan/get_testscript?epic=${epic}&feature=${feature}&story=${story}`
      );
      if (res.code !== 200) {
        return this.$message.error("查询失败");
      }
      console.log(res.data)
      return res.data
    },

    // 添加任务
    async addJob() {
      console.log(this.addTaskplanForm)
      const {data: res} = await this.$http.post('/taskplan/add_job', this.addTaskplanForm, {
          headers: { "Content-Type": "application/json;charset=UTF-8" },
        })
        if (res.code !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg);
      this.addTaskplanDialogVisibal = false
      this.getTaskplanList();
    },

    // 关闭添加任务计划表单
    closeAddTaskplanForm(formName) {
      this.addTaskplanDialogVisibal = false
      console.log(this.$refs[formName])
      this.$refs[formName].resetFields();
    }

  },

};
</script>
<style lang="less" scoped>
/deep/ .el-date-editor,
.el-input,
.el-input--prefix,
.el-input--suffix,
.el-date-editor--datetime {
  width: 100% !important;
  font-size: 12px;
}
/deep/.cron input {
  padding: 5px;
}
/deep/.el-cascader {
  width: 100%;
}
/deep/ .el-cascader-panel{
  height: 400px !important;
  // overflow: auto !important;
}
/deep/ .el-cascader-menu{
  height: 300px  !important;
}
</style>
